package ufc.si.pet.dao.implementacoes;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.criteria.CriteriaQuery;
import ufc.si.pet.dao.interfaces.GenericDAO;
import ufc.si.pet.util.JPAUtil;

public class GenericJpaDAO<T> implements GenericDAO<T>{

	protected EntityManager entityManager;
	protected Class<T> persistentClass;
	
	public GenericJpaDAO() {
		entityManager = JPAUtil.getEntityManager();
	}
	
	@Override
	public void salvar(T entidade) {
		entityManager.persist(entidade);
	}

	@Override
	public void excluir(T entidade) {
		Object o = entityManager.merge(entidade);
		entityManager.remove(o);
	}

	@Override
	public void atualizar(T entidade) {
		Object o = entityManager.merge(entidade);
		entityManager.merge(o);
	}

	@Override
	public List<T> listar() {
		CriteriaQuery<T> criteria = entityManager.getCriteriaBuilder().createQuery(persistentClass);
		criteria.from(persistentClass);
		return entityManager.createQuery(criteria).getResultList();
	}

	@Override
	public T find(long id) {
		return entityManager.find(persistentClass, id);
	}

	@Override
	public void beginTransaction() {
		entityManager.getTransaction().begin();
		System.err.println("Iniciado transação pelo EntityManager: "+persistentClass.getSimpleName());
	}

	@Override
	public void commit() {
		EntityTransaction et = entityManager.getTransaction();
		if(et.isActive())
			et.commit();
		System.err.println("Commit completado pelo EntityManager: "+persistentClass.getSimpleName());
	}

	@Override
	public void rollback() {
		// TODO Auto-generated method stub
		EntityTransaction et = entityManager.getTransaction();
		if(et.isActive())
			et.rollback();
		System.err.println("RollBack gerado pelo EntityManager: "+persistentClass.getSimpleName());
	}

	@Override
	public void close() {
		entityManager.close();
		System.err.println("Encerrado EntityManager: "+persistentClass.getSimpleName());
	}
}